You can cancel a job simply by calling cancel()
on it.
If you run this snippet, the first coroutine is canceled by the second
coroutine. The first coroutine is blocking on the delay()
when the
second coroutine cancels it, so the first coroutine never completes the
work, including never printing the "after the first delay" message.
You can learn more about this in:
Tags:
xxxxxxxxxx
1
import kotlinx.coroutines.*
2
3
fun main() {
4
val job = GlobalScope.launch(Dispatchers.Main) {
5
println("This is executed before the first delay")
6
stallForTime()
7
println("This is executed after the first delay")
8
}
9
10
GlobalScope.launch(Dispatchers.Main) {
11
println("This is executed before the second delay")
12
job.cancel()
13
stallForTime()
14
println("This is executed after the second delay")
15
}
16
17
println("This is executed immediately")
18
}
19
20
suspend fun stallForTime() {
21
withContext(Dispatchers.Default) {
22
delay(2000L)
23
}
24
}